<?php
// +----------------------------------------------------------------------
// | author: thinkphp
// +----------------------------------------------------------------------

namespace app\api\lists\line;

use app\api\lists\BaseApiDataLists;
use app\common\enum\YesNoEnum;
use app\common\lists\ListsSearchInterface;
use app\common\model\travel\Line;

/**
 * 列表
 * Class LineLists
 * @package app\api\lists\line
 */
class LineLists extends BaseApiDataLists implements ListsSearchInterface
{

    /**
     * @notes 搜索条件
     * @return \string[][]
     */
    public function setSearch(): array
    {
        return [
            '=' => ['is_hot']
        ];
    }


    /**
     * @notes 自定查询条件
     * @return array
     */
    public function queryWhere()
    {
        $where[] = ['l.status', '=', 1];
        if (!empty($this->params['keyword'])) {
            $where[] = ['l.tags', 'like', '%' . $this->params['keyword'] . '%'];
        }
        if (!empty($this->params['is_hot'])) {
            $where[] = ['l.is_hot', '=', YesNoEnum::YES];
        }
        return $where;
    }


    /**
     * @notes 获取列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function lists(): array
    {

//        $where[] = ['l.status', '=', 1];
//        if (!empty($this->params['keyword'])) {
//            $where[] = ['l.tags', 'like', '%' . $this->params['keyword'] . '%'];
//        }
//        if (!empty($this->params['is_hot'])) {
//            $where[] = ['l.is_hot', '=', YesNoEnum::YES];
//        }

        $orderRaw = 'l.sort desc, l.id desc,l.is_hot desc,p.create_time DESC';
        // 查询最近一天的价格记录
        $result = Line::alias('l')
            ->leftJoin('line_price p', 'l.id = p.line_id')
            ->where($this->queryWhere())
            ->where($this->searchWhere)
            ->where('p.create_time', '>=', date('Y-m-d H:i:s', strtotime('-1 day')))
            ->field([
                'l.*',
                'p.price as price', // 获取当天价格
                'p.create_time' // 记录价格创建时间
            ])
            ->orderRaw($orderRaw) // 优先展示最新价格
            ->group('l.id') // 避免重复线路
            ->limit($this->limitOffset, $this->limitLength)
            ->select()
            ->toArray();
        return $result;
    }


    /**
     * @notes 获取数量
     * @return int
     */
    public function count(): int
    {
        return Line::alias('l')
            ->where($this->queryWhere())
            ->count();
    }
}